//
//  SHKitMediaFetcher.m
//  Netease
//
//  Created by 王方伟 on 2017/12/25.
//  Copyright © 2017年 wfw. All rights reserved.
//

#import "SHKitMediaFetcher.h"
#import <MobileCoreServices/MobileCoreServices.h>
#import "SHAlertAction.h"

@interface SHKitMediaFetcher ()<TZImagePickerControllerDelegate>
@property (nonatomic,copy)   NIMKitLibraryFetchResult libraryResultHandler;
@property (nonatomic,copy)   NIMKitCameraFetchResult  cameraResultHandler;
@property (nonatomic,strong) TZImagePickerController *assetsPicker;
@end

@implementation SHKitMediaFetcher

- (void)fetchPhotoFromLibrary:(NIMKitLibraryFetchResult)result{
    __weak typeof(self) weakSelf = self;
    [self setUpPhotoLibrary:^(TZImagePickerController * _Nullable picker) {
        if (picker && weakSelf) {
            weakSelf.assetsPicker = picker;
            weakSelf.libraryResultHandler = result;
            [[UIApplication sharedApplication].keyWindow.rootViewController presentViewController:picker animated:YES completion:nil];
            
        }else{
            result(nil,nil,PHAssetMediaTypeUnknown);
        }
    }];
}


- (void)setUpPhotoLibrary:(void(^)(TZImagePickerController * _Nullable picker)) handler{
    __weak typeof(self) weakSelf = self;
    [PHPhotoLibrary requestAuthorization:^(PHAuthorizationStatus status){
        dispatch_async(dispatch_get_main_queue(), ^{
            if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) {
                UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:@"相册权限受限" preferredStyle:UIAlertControllerStyleActionSheet];
                SHAlertAction *action = [SHAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:nil];
                [alertVC addAction:action];
                [DCURLRouter presentViewController:alertVC animated:YES completion:nil];
                
                if(handler) handler(nil);
            }
            if (status == PHAuthorizationStatusAuthorized) {
                SHKitMediaPickerController *vc = [[SHKitMediaPickerController alloc] initWithMaxImagesCount:self.limit delegate:weakSelf];
                vc.naviBgColor = [UIColor blackColor];
                vc.naviTitleColor = [UIColor whiteColor];
                vc.barItemTextColor = [UIColor whiteColor];
                vc.navigationBar.barStyle = UIBarStyleDefault;
                vc.oKButtonTitleColorNormal = [UIColor redColor];
                vc.oKButtonTitleColorDisabled = [UIColor redColor];
                vc.allowPickingVideo = [self.mediaTypes containsObject:(NSString *)kUTTypeMovie];
                if(handler) handler(vc);
            }
        });
    }];
}
@end


@implementation SHKitMediaPickerController

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [UIApplication sharedApplication].statusBarStyle =  UIStatusBarStyleDefault;
}

@end
